package nine_Chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ServerReaderThreadDuanToDuan extends Thread{
    private Socket s;

    public ServerReaderThreadDuanToDuan(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try(BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
            String line;
            System.out.println(1);
            while ((line = br.readLine()) != null) {
                System.out.println(2);
                System.out.println("Receive msg from " + Thread.currentThread().getName() + " : " + line);
                sendMsgToAllClient(line);
            }
            System.out.println(3);
        } catch (IOException e) {
            System.out.println("有人下线了!");
            Server.allSocketOnline.remove(s);
        }
    }

    private void sendMsgToAllClient(String msg) {
        for (Socket s : Server.allSocketOnline) {
            try {
                PrintStream ps = new PrintStream(s.getOutputStream());
                ps.println(msg);
                ps.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
